<?php

namespace App\Http\Controllers\Stock\Manage;

use App\Http\Controllers\ShopController;
use App\Models\Business\Source as SourceModel;
use Illuminate\Support\Facades\Validator;

class SourceController extends ShopController
{
    public function index()
    {
        $sourceList = SourceModel::OrderBy('id','desc')->get();

        if(count($sourceList) > 0)
        {
            return $this->success('查询成功',$sourceList);
        }else{
            return $this->error('暂无数据');
        }
    }

    public function add()
    {
        $name = request('name','');

        $data = [
            'name' => $name
        ];

        // 定义验证器
        $validate = [
            [
                'name' => ['required','unique:business_source']
            ],
            [
                'name.required' => '客户来源名称必填',
                'name.unique' => '客户来源名称已存在'
            ]
        ];

        // 创建验证器
        $validator = Validator::make($data,...$validate);

        if($validator->fails())
        {
           return $this->error($validator->errors()->first());
        }

        $result = SourceModel::create($data);

        if($result === false)
        {
            return $this->error('添加失败');
        }else{
            return $this->success('添加成功');
        }
    }

    public function edit()
    {
        $name = request('name','');
        $id = request('id',0);
        $data = [
            'name' => $name
        ];

        // 定义验证器
        $validate = [
            [
                'name' => ['required','unique:business_source']
            ],
            [
                'name.required' => '客户来源名称必填',
                'name.unique' => '客户来源名称没有修改'
            ]
        ];

        // 创建验证器
        $validator = Validator::make($data,...$validate);

        if($validator->fails())
        {
           return $this->error($validator->errors()->first());
        }

        $result = SourceModel::where('id',$id)->update($data);

        if($result === false)
        {
            return $this->error('更新失败');
        }else{
            return $this->success('更新成功');
        }
    }

    public function del()
    {
        $id = request('id',0);
        
        $result = SourceModel::destroy ($id);

        if($result === false)
        {
            return $this->error('删除失败');
        }else{
            return $this->success('删除成功');
        }

    }

    public function name()
    {
        $id = request('id',0);
        // return $id;
        $result = SourceModel::where('id',$id)->first();

        if($result)
        {
            return $this->success('获取成功',$result);
        }else{
            return $this->error('获取失败');
        }
    }
}
